package util;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import org.springframework.boot.web.servlet.context.ServletWebServerInitializedEvent;
import org.springframework.context.ApplicationEvent;

public abstract class AppEventUtil {
	
	private static final List<ApplicationEventDTO> events = new LinkedList<>();
	
	
	private static volatile int port;
	
	public static synchronized void add(ApplicationEvent event) {
		if(event==null) {
			return;
		}
		events.add(new ApplicationEventDTO(event));
		if(event instanceof ServletWebServerInitializedEvent) {
			ServletWebServerInitializedEvent e = (ServletWebServerInitializedEvent)event;
			int port = e.getWebServer().getPort();
			AppEventUtil.port = port;
		}
	}
	
    public static synchronized List<ApplicationEventDTO>  all() {
    	List<ApplicationEventDTO> list = new ArrayList<>();
    	list.addAll(events);
    	return list;  	
	}
    
    
    public static class ApplicationEventDTO{
    	// public  final ApplicationEvent event;
    	public  final String type;
    	public  final String time;
    	public  final String thread;
    	
    	public ApplicationEventDTO(ApplicationEvent event) {
    		this.type = event.getClass().getName();
    		this.time = LocalDateTime.now().toString();
    		this.thread = Thread.currentThread().getName();
    	}

    }
    
    public static int getPort() {
    	return port;
    }

}